package com.sdy.supermarket.task.iporder;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.sdy.approval.api.ApprovalAllApi;
import com.sdy.approval.biz.model.TpApproveFlowConfig;
import com.sdy.mvc.annotation.TaskSync;
import com.sdy.supermarket.biz.mapper.GsAppIpApplyMapper;
import com.sdy.supermarket.biz.mapper.GsAppIpMapper;
import com.sdy.supermarket.biz.mapper.GsIpChangeMapper;
import com.sdy.supermarket.biz.model.GsAppIp;
import com.sdy.supermarket.biz.model.GsAppIpApply;
import com.sdy.supermarket.biz.model.GsIpChange;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 定时查询数据库中待审批的IP订单并且发送给流程审批模块
 *
 * @author hyh
 */
@Component
@Slf4j
public class IpOrderTask {

    @Resource
    private GsAppIpApplyMapper gsAppIpApplyMapper;
    @Autowired
    private ApprovalAllApi approvalAllApi;
    @Resource
    private GsIpChangeMapper gsIpChangeMapper;
    @Resource
    private GsAppIpMapper gsAppIpMapper;


    /**
     * 向流程审核模块发送需要审核的订单
     *
     * @throws Exception
     */
    @Scheduled(cron = "0/30 * * * * ?")
    @TaskSync
    public void sendIpOrderList() throws Exception {
        List<GsAppIpApply> appIpApplies = gsAppIpApplyMapper.selectList(Wrappers.<GsAppIpApply>lambdaQuery().eq(GsAppIpApply::getState, 2));
        if (appIpApplies.size() != 0) {
            List<Map<String, Object>> list = new ArrayList<>();
            appIpApplies.forEach(ip -> {
                Map<String, Object> map = new HashMap<>();
                map.put("order_item_no", ip.getApplyNo());
                map.put("res_id", "[政务超市]1024");
                map.put("user_id", ip.getUserId());
                list.add(map);
                // 添加完成后将订单状态发送改变为已发送
                ip.setState(3);
            });
            // 查询是否存在这个流程，如果不存在则生成
            List<TpApproveFlowConfig> flowConfigs = approvalAllApi.selectApprovalByResId("[政务超市]1024");
            if (flowConfigs.size() == 0) {
                // 默认只有部门为1和角色为1的用户能够审核
                approvalAllApi.insertApproval(Arrays.asList(18), Arrays.asList(1), "[政务超市]", 1024 + "");
            }
            int batchUpdate = gsAppIpApplyMapper.batchUpdate(appIpApplies);
            Integer lookResId = approvalAllApi.lookResId(list);
            if (batchUpdate == 0 || lookResId == 0) {
                log.error("向流程审批模块发送IP修改单数据时出现错误");
            }
        }
    }


    /**
     * 查询到已经完成并且通过审核的IP修改申请单，并且将所申请的内容发放出去
     */
    @Scheduled(cron = "0/30 * * * * ?")
    @TaskSync
    public void setIpOrderByIpChange() {
        List<GsAppIpApply> appIpApplies = gsAppIpApplyMapper.selectList(Wrappers.<GsAppIpApply>lambdaQuery().eq(GsAppIpApply::getState, 6).eq(GsAppIpApply::getIsDone, 0));
        if (appIpApplies.size() == 0) {
            log.info("本次没有需要发放的IP修改申请单");
        } else {
            StringBuffer ipIdList = new StringBuffer();
            appIpApplies.forEach(app -> {
                ipIdList.append(app.getIpId());
            });
            List<String> changeIpIdList = Arrays.asList(new String(ipIdList).split(","));
            // 查询到需要发放的IP数据
            List<GsIpChange> ipChangeList = gsIpChangeMapper.selectList(Wrappers.<GsIpChange>lambdaQuery().in(GsIpChange::getId, changeIpIdList));
            // 拆分过滤出新增的IP数据
            List<GsIpChange> isAddIpDate = ipChangeList.stream().filter(ip -> ip.getAimsId() == null).collect(Collectors.toList());
            List<GsAppIp> addAppIps = new ArrayList<>();
            isAddIpDate.forEach(addIp -> {
                addAppIps.add(new GsAppIp().setCreateTime(new Date()).setAppId(addIp.getAppId()).setIp(addIp.getIp()).setResIdList(addIp.getResIdList()));
            });
            if (!addAppIps.isEmpty()) {
                // 执行批量添加IP方法
                gsAppIpMapper.batchInsert(addAppIps);
                log.info("本次发放IP修改单审核通过的IP数量为:" + addAppIps.size());
            }
            // 过滤出修改的IP数据
            List<GsIpChange> isUpdateIpDate = ipChangeList.stream().filter(ip -> ip.getAimsId() != null).collect(Collectors.toList());
            List<GsAppIp> updateAppIps = new ArrayList<>();
            isUpdateIpDate.forEach(updateIp -> {
                updateAppIps.add(new GsAppIp().setId(updateIp.getAimsId()).setIp(updateIp.getIp())
                        .setResIdList(updateIp.getResIdList()).setAppId(updateIp.getAppId()).setCreateTime(new Date()));
            });
            if (!updateAppIps.isEmpty()) {
                // 执行批量修改IP方法
                gsAppIpMapper.batchUpdate(updateAppIps);
                log.info("本次修改IP修改单审核通过的IP数量为:" + updateAppIps.size());
            }
            appIpApplies.forEach(gsAppIpApply -> {
                gsAppIpApply.setIsDone(1);
            });
            // 更新订单是否已完成状态为已完成
            gsAppIpApplyMapper.batchUpdate(appIpApplies);
        }
    }

}
